package com.tiger.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tiger.mapper.base.UserMapper;
import com.tiger.pojo.base.User;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 * @author HuXuehao (StudiousTiger)
 * @desc 这个类的作用是
 * @date 2022/2/22
 */

@Slf4j
@RestController
public class FileController {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;
    @Value("${minio.bucketNameOfAD}")
    private String bucketNameOfAD;
    @Value("${minio.bucketNameOfXls}")
    private String bucketNameOfXls;
    @Value("${minio.endPoint}")
    private String endPoint;

    @Autowired
    HttpServletRequest httpServletRequest; //通过注解获取一个request


    /**
     * 文件上传（头像）
     * @param file
     * @return
     */
    @PostMapping(value = "/file/upload", name = "文件上传（头像）/user")
    public String upload(@RequestParam(name = "file", required = false) MultipartFile file){
        if (file == null){
            return "false";
        }
        String fileName = httpServletRequest.getSession().getAttribute("userId")+".jpg";
        String url = putImgAndGetUrl(file, fileName);

        // 将头像存到数据库中
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id",httpServletRequest.getSession().getAttribute("userId"));
        updateWrapper.set("user_head_portrait",fileName);
        userMapper.update(null,updateWrapper);

        return url;
    }
    private String putImgAndGetUrl(MultipartFile file, String fileName){
        InputStream in = null;
        try {

            // 判断目标 bucket 是否存在
            boolean exit = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!exit){
                // 创建名为 bucketName 的 bucket
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }

            in = file.getInputStream();
            // 上传图片
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .stream(in,file.getSize(),-1)
                            .build()
            );

            //获取头像路径
            String url = minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs
                            .builder()
                            .method(Method.GET)
                            .bucket(bucketName)
                            .object(fileName)
                            .build());
            return url;
        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        }finally {
            // 关闭流
            if (in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 文件的下载
     * @param response
     * @param fileName
     */
    @RequestMapping(value = "/file/download/{fileName}", name = "文件的下载/user")
    public void download(HttpServletResponse response,@PathVariable String fileName){
        InputStream in = null;
        try {
            // 获取对象的信息
            StatObjectResponse stat = minioClient.statObject(
                    StatObjectArgs.builder().bucket(bucketName).build()
            );
            // 设置内容类型
            response.setContentType(stat.contentType());
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
            // 文件下载
            in = minioClient.getObject(
                    GetObjectArgs.builder().bucket(bucketName).build()
            );
            IOUtils.copy(in,response.getOutputStream());
        } catch (Exception e){
            log.error(e.toString());
        } finally {
            if (in != null){
                try{
                    in.close();
                } catch (Exception e){
                    log.error(e.toString());
                }
            }
        }
    }
}
